<%@ page import="util.JDBC" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="util.JSON" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.DateFormat" %>
<%@ page pageEncoding="utf-8"%>
<%
    //设置服务器端以UTF-8编码进行输出
    response.setCharacterEncoding("utf-8");
    //设置浏览器以UTF-8编码进行接收,解决中文乱码问题
    response.setContentType("application/json; charset=utf-8");
    PrintWriter writer = response.getWriter();

    //    Cookie的使用
    Cookie[] cookies=request.getCookies();
    boolean visitFlag=false;
    for(int i=0;i<cookies.length;i++){
        if(cookies[i].getName().equals("lastAccessTime")){
            System.out.println("此浏览器上次访问的时间是：");
            Long lastAccessTime=Long.parseLong(cookies[i].getValue());
            Date date=new Date(lastAccessTime);
            System.out.println(DateFormat.getInstance().format(date));
            visitFlag=true;
        }
    }
    if(visitFlag==false){
        System.out.println("这是浏览器第一次访问本站！");
    }
    Cookie cookie=new Cookie("lastAccessTime",System.currentTimeMillis()+"");
    cookie.setMaxAge(24*60*60);//设置一天
    System.out.println("lastAccessTime保存时间："+cookie.getMaxAge());
    //将cookie对象添加到response对象中，这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
    response.addCookie(cookie);

    //处理请求
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    String sql="select id from user where username='"+username+"' and password='"+password+"'";
    System.out.println(sql);
    JDBC.connectionTest();
    ResultSet rs=JDBC.executeQuery(sql);
    JDBC.connectionTest();
    int userId=-1;
    while (rs.next()){
        userId=rs.getInt("id");
    }
    JSON json=null;
    //管理员账号
    if(userId==1){
        session.setAttribute("userId",String.valueOf(userId));
        session.setAttribute("username",username);
        json=new JSON("status","managetor");
        json.put("message","登录成功！！！");
    }else if(userId!=-1){    //普通账号
        session.setAttribute("userId",String.valueOf(userId));
        session.setAttribute("username",username);
        json=new JSON("status","success");
        json.put("message","登录成功！！！");
    }else{
        json=new JSON("status","failed");
        json.put("message","账号或密码错误!!!");
    }
    writer.write(json.getJson());
    writer.close();
%>